import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:app_30/res/colors.dart';
import 'package:app_30/res/gaps.dart';
import 'package:app_30/util/cache_utils.dart';
import 'package:app_30/util/toast_utils.dart';
import 'package:app_30/widgets/load_image.dart';
import 'package:app_30/widgets/my_app_bar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qr_flutter/qr_flutter.dart';

class ShareQrPage extends StatefulWidget {
  const ShareQrPage({Key? key}) : super(key: key);

  @override
  State<ShareQrPage> createState() => _ShareQrPageState();
}

class _ShareQrPageState extends State<ShareQrPage> {
  GlobalKey _globalKey = GlobalKey();
  List<Uint8List> images = List.empty(growable: true);

  @override
  void initState() {
    super.initState();
    _requestPermission();
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future<void> testShare() async {
    try {
      final channel = const MethodChannel('channel:Chenli');
      final String nativeSay = await channel.invokeMethod('openWechat');
      print("--------${nativeSay}");
    } catch (e) {
      print(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        isBack: true,
        centerTitle: '二维码分享',
        actionName: '分享',
        onPressed: testShare,
      ),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        color: Colours.app_main,
        child: Column(
          children: <Widget>[
            Gaps.vGap50,
            Center(
              child: RepaintBoundary(
                key: _globalKey,
                child: Stack(
                  alignment: AlignmentDirectional.bottomCenter,
                  children: <Widget>[
                    LoadAssetImage(
                      'hb_img_z',
                      width: 260,
                      height: 370,
                      fit: BoxFit.fill,
                    ),
                    Positioned(
                      bottom: 0,
                      child: Container(
                        width: 150,
                        height: 150,
                        margin: EdgeInsets.fromLTRB(0, 0, 0, 40),
                        child: QrImage(
                          data: '${getTgUrl()}',
                          version: QrVersions.auto,
                          foregroundColor: Colors.black,
                          //前景色
                          backgroundColor: Colors.white,
                          size: 200.0,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Expanded(
              child: Container(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end, //垂直方向居中对齐
                  children: <Widget>[
                    TextButton(
                      child: Text("保存图片"),
                      //添加一个点击事件
                      onPressed: _saveScreen,
                      //设置按钮是否自动获取焦点
                      autofocus: true,
                      //定义一下文本样式
                      style: buildButtonStyle(),
                    ),
                  ],
                ),
              ),
            ),
            Gaps.vGap16,
            Text(
              "保存图片，可以分享到微信朋友圈和QQ空间，给你的好友哦！",
              style: TextStyle(
                color: Colors.white,
                fontSize: 12,
              ),
            ),
            Gaps.vGap16,
          ],
        ),
      ),
    );
  }

  _requestPermission() async {
    Map<Permission, PermissionStatus> statuses = await [
      Permission.storage,
    ].request();

    final info = statuses[Permission.storage].toString();
    print(info);
    Toast.show(info);
  }

  _saveScreen() async {
    RenderRepaintBoundary boundary =
        _globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    ui.Image image = await boundary.toImage();
    ByteData? byteData = await (image.toByteData(format: ui.ImageByteFormat.png)
        as FutureOr<ByteData?>);
    if (byteData != null) {
      final result =
          await ImageGallerySaver.saveImage(byteData.buffer.asUint8List());
      print(result);
      Toast.show(result.toString());
      if (Platform.isIOS) {
        if (result) {
          Toast.show('保存成功');
        } else {
          Toast.show('保存失败');
        }
      } else {
        if (result != null) {
          Toast.show('保存成功');
        } else {
          Toast.show('保存失败');
        }
      }
    }
  }
}

ButtonStyle buildButtonStyle() {
  return ButtonStyle(
    //定义文本的样式 这里设置的颜色是不起作用的
    textStyle: MaterialStateProperty.all(
        TextStyle(fontSize: 15, color: Colours.app_main)),
    //设置按钮上字体与图标的颜色
    //foregroundColor: MaterialStateProperty.all(Colors.deepPurple),
    //更优美的方式来设置
    foregroundColor: MaterialStateProperty.resolveWith(
      (states) {
        if (states.contains(MaterialState.focused) &&
            !states.contains(MaterialState.pressed)) {
          //获取焦点时的颜色
          return Colors.white;
        } else if (states.contains(MaterialState.pressed)) {
          //按下时的颜色
          return Colors.white70;
        }
        //默认状态使用灰色
        return Colors.white;
      },
    ),
    //背景颜色
    backgroundColor: MaterialStateProperty.resolveWith((states) {
      //设置按下时的背景颜色
      if (states.contains(MaterialState.pressed)) {
        return Colours.shadow_blue;
      }
      //默认不使用背景颜色
      return Colours.shadow_blue;
    }),
    //设置水波纹颜色
    overlayColor: MaterialStateProperty.all(Colours.shadow_blue),
    //设置阴影  不适用于这里的TextButton
    elevation: MaterialStateProperty.all(1),
    //设置按钮内边距
    padding: MaterialStateProperty.all(EdgeInsets.fromLTRB(40, 10, 40, 10)),
    //设置按钮的大小
    // minimumSize: MaterialStateProperty.all(Size(double.infinity, 20)),
    //设置边框
    // side: MaterialStateProperty.all(BorderSide(color: Colors.grey, width: 1)),
    //外边框装饰 会覆盖 side 配置的样式
    // shape: MaterialStateProperty.all(StadiumBorder()),
  );
}
